<template>
  <div class="flex w-full h-[100vh]">
    <div class="left-side w-[56%]">
      <img class="w-full h-full object-cover" src="@/assets/login/left_bg.png" alt="logo" />
    </div>
    <div class="right-side w-[44%] p-[40px] flex flex-col relative">
      <!-- 头部导航 -->
      <div class="flex items-center justify-between absolute top-0 right-0 left-0 p-[40px]">
        <div class="cursor-pointer back_svg_view" @click="goBack">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="32"
            height="32"
            viewBox="0 0 32 32"
            fill="none">
            <path
              d="M11.293 8.89258C11.6835 8.50247 12.3166 8.50224 12.707 8.89258C13.0972 9.28299 13.0971 9.91615 12.707 10.3066L8.0127 15H20.5029L20.6045 15.0049C21.1089 15.0559 21.5029 15.4821 21.5029 16C21.5029 16.5178 21.1089 16.9441 20.6045 16.9951L20.5029 17H8.01465L12.707 21.6924C13.0973 22.0828 13.097 22.7159 12.707 23.1064C12.3165 23.4969 11.6835 23.4969 11.293 23.1064L4.89258 16.707C4.50217 16.3166 4.50227 15.6835 4.89258 15.293L11.293 8.89258ZM25.5996 8.59961C26.1518 8.59961 26.5995 9.0474 26.5996 9.59961V22.3994C26.5996 22.9517 26.1519 23.3994 25.5996 23.3994C25.0474 23.3994 24.5996 22.9517 24.5996 22.3994V9.59961C24.5997 9.04744 25.0474 8.59967 25.5996 8.59961Z"
              fill="#222222" />
          </svg>
        </div>
        <Logo width="150" height="40" />
      </div>

      <!-- 登录表单 -->
      <div class="flex-1 flex flex-col justify-center">
        <div class="max-w-[440px] mx-auto" v-if="step == 1">
          <!-- 表单区域 -->
          <div>
            <!-- 标题区域 -->
            <div class="text-center mb-[40px]">
              <h1 class="text-[32px] font-bold text-[#0A0A0A] mb-[16px]">
                Enter your email to continue
              </h1>
              <p class="text-[#7A7A7A] text-sm">
                An account will be automatically created for new users.
              </p>
            </div>
            <!-- 邮箱输入 -->
            <div>
              <label class="text-sm font-medium text-[#0A0A0A]">Email address</label>
              <el-input
                v-model="email"
                placeholder="Enter your Email address"
                type="email"
                size="large"
                class="bg-[#F4F5F7] rounded-[8px]"
                :class="{ 'is-error': emailError }"
                @input="clearEmailError"
                @keyup.enter="handleGetVerificationCode" />
              <div v-if="emailError" class="text-red-500 text-xs">
                {{ emailError }}
              </div>

              <el-button
                type="primary"
                size="large"
                :loading="isLoading"
                :disabled="!isEmailValid || isLoading"
                @click="handleGetVerificationCode"
                class="w-full h-[48px] mt-[24px] text-base font-medium"
                style="border-radius: 30px">
                <span v-if="!isLoading" class="get_code_text">Get Verification Code</span>
              </el-button>
            </div>
          </div>

          <!-- 协议条款 -->
          <div class="mt-[16px] text-center agreement_view">
            <div @click="agreement = !agreement">
              <AgreeIcon :agreed="agreement" />
            </div>
            <p class="text-xs text-[#7A7A7A] leading-relaxed ml-[4px]">
              By continuing, you agree to our
              <span @click="goTerms" class="cursor-pointer color_text">Terms of Service</span>
              and
              <span @click="goPrivacy" class="cursor-pointer color_text">Privacy Policy</span>
            </p>
          </div>

          <!-- 谷歌登录 -->
          <!-- <div class="py-[8px]">
                        <el-divider content-position="center">Or</el-divider>
                     </div> -->
        </div>

        <!-- 验证码 -->
        <div class="max-w-[440px] mx-auto" v-else-if="step == 2">
          <!-- 验证码输入 (显示条件) -->
          <div class="space-y-4">
            <div class="text-center">
              <label class="text-[32px] font-bold text-[#0A0A0A] block mb-[16px]">
                Verify your email
              </label>
              <div class="text-[#7A7A7A] text-[16px]">
                Enter the verification code sent to your email
              </div>
              <div
                @click="step = 1"
                class="cursor-pointer mb-[16px] mt-[4px] flex items-center justify-center">
                <span class="text-[#7A7A7A] text-[16px] email_text">{{ email }}</span>
                <EditIcon class="ml-[3px]" />
              </div>
            </div>

            <VerificationCodeInput
              v-model="verificationCode"
              :error="codeError"
              @complete="handleVerifyCode" />
          </div>
          <!-- 倒计时显示 -->
          <div class="text-center text-[16px] text-[#7A7A7A] mt-[20px]">
            <span class="cursor-pointer email_text" @click="handleResendCode">
              Didn't receive a code?
            </span>
            <span class="cursor-pointer email_text" @click="handleResendCode">Resend</span>
            <span v-if="countdown > 0">({{ countdown }})</span>
          </div>
        </div>
      </div>

      <div v-if="dialogVisible" class="agree_view">
        <div class="title agree_content">Terms and Policies</div>
        <div class="mt-[16px] des_text">
          <span>
            Before signing up to Nexbie, please read our
            <span class="color_text cursor-pointer" @click="goTerms">Terms of</span>
          </span>
          <br />
          <span class="color_text cursor-pointer" @click="goTerms">Service</span>
          and
          <span class="color_text cursor-pointer" @click="goPrivacy">Privacy Policy</span>
          .Continuing to sign up means that you agree our terms and polices.
        </div>
        <div class="flex_row mt-[24px]">
          <div class="cancel_btn cursor-pointer" @click="dialogVisible = false">Cancel</div>
          <div class="confirm_btn cursor-pointer ml-[24px]" v-hover-bg @click="agreeContinue">
            Agree & Continue
          </div>
        </div>
      </div>
    </div>

    <Overlay :visible="dialogVisible" class="agree_content"></Overlay>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, onUnmounted } from 'vue';
  import { useRouter } from 'vue-router';
  import Logo from '@/components/icons/logo.vue';
  import { UserAPI } from '@/api/user';
  import { useUserStore } from '@/store/user';
  import VerificationCodeInput from '@/components/VerificationCodeInput.vue';
  import Overlay from '@/components/Overlay.vue';
  import EditIcon from '@/components/icons/EditIcon.vue';
  import AgreeIcon from '@/components/icons/AgreeIcon.vue';

  const router = useRouter();
  const userStore = useUserStore();

  // 响应式数据
  const email = ref('');
  const verificationCode = ref('');
  const showVerificationCode = ref(false);
  const isLoading = ref(false);
  const countdown = ref(0);
  const emailError = ref('');
  const codeError = ref('');
  const agreement = ref(false);
  const step = ref(1);
  const dialogVisible = ref<boolean>(false); // 隐私协议modal

  // 计算属性
  const isEmailValid = computed(() => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email.value);
  });

  const isResendDisabled = computed(() => {
    return countdown.value > 0 || isLoading.value;
  });

  const resendText = computed(() => {
    return countdown.value > 0 ? `${countdown.value}s` : 'Resend';
  });

  // 定时器
  let countdownTimer: any = null;

  // 方法
  const goBack = () => {
    if (step.value === 2) {
      step.value = 1;
      return;
    }
    router.go(-1);
  };

  const goTerms = () => {
    router.push('/terms');
  };

  const goPrivacy = () => {
    router.push('/privacy');
  };

  const clearEmailError = () => {
    emailError.value = '';
  };

  const clearCodeError = () => {
    codeError.value = '';
  };

  const validateEmail = () => {
    if (!email.value) {
      emailError.value = 'Please enter your email address';
      return false;
    }
    if (!isEmailValid.value) {
      emailError.value = 'Please enter a valid email address';
      return false;
    }
    return true;
  };

  const validateVerificationCode = () => {
    if (!verificationCode.value) {
      codeError.value = 'Please enter verification code';
      return false;
    }
    if (verificationCode.value.length !== 6) {
      codeError.value = 'Verification code must be 6 digits';
      return false;
    }
    return true;
  };

  const startCountdown = () => {
    countdown.value = 60;
    countdownTimer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(countdownTimer!);
        countdownTimer = null;
      }
    }, 1000);
  };

  const agreeContinue = () => {
    agreement.value = true;
    dialogVisible.value = false;
    handleGetVerificationCode();
  };

  const handleGetVerificationCode = async () => {
    if (!validateEmail()) return;
    if (!agreement.value) {
      dialogVisible.value = true;
      return;
    }

    isLoading.value = true;
    emailError.value = '';
    verificationCode.value = '';

    try {
      // 模拟API调用
      await UserAPI.getCode({
        email: email.value,
      });
      step.value = 2;
      showVerificationCode.value = true;
      startCountdown();

      // 这里可以添加实际的API调用
      // await sendVerificationCode(email.value)
    } catch (error) {
      emailError.value = 'Failed to send verification code. Please try again.';
      console.error('Send verification code error:', error);
    } finally {
      isLoading.value = false;
    }
  };

  const handleResendCode = async () => {
    if (isResendDisabled.value) return;

    await handleGetVerificationCode();
  };

  const handleVerifyCode = async (code?: string) => {
    const codeToVerify = code || verificationCode.value;

    if (!codeToVerify || codeToVerify.length !== 6) {
      codeError.value = 'Please enter a complete 6-digit code';
      return;
    }

    isLoading.value = true;
    codeError.value = '';

    try {
      // 调用登录API
      const res = await UserAPI.login({ email: email.value, code: codeToVerify, source_type:2 });
      // 存储用户信息到store
      userStore.loginSuccess(res);
      // 跳转到主页
      setTimeout(() => {
        router.push('/');
      }, 500);
    } catch (error) {
      codeError.value = 'Invalid verification code';
      console.error('Verify code error:', error);
    } finally {
      isLoading.value = false;
    }
  };

  // 清理定时器
  onUnmounted(() => {
    if (countdownTimer) {
      clearInterval(countdownTimer);
    }
  });
</script>

<style lang="scss" scoped>
  .right-side {
    background: #fff;
  }

  :deep(.el-input) {
    .el-input__wrapper {
      border-radius: 8px;
      border: none;
      box-shadow: none;
      transition: all 0.3s ease;
      background: #f4f5f7;
      color: #0a0a0a;
    }

    &.is-error .el-input__wrapper {
      border-color: #f56565;
      box-shadow: 0 0 0 2px rgba(245, 101, 101, 0.1);
    }
  }

  :deep(.el-button) {
    border-radius: 8px;
    font-weight: 500;

    &.el-button--primary {
      background: #f76b1b;
      border-color: #f76b1b;

      &:hover {
        background: #e55a0f;
        border-color: #e55a0f;
      }

      &:disabled {
        background: #e0e0e0;
        border-color: #e0e0e0;
        color: #9ca3af;
      }
    }
  }

  :deep(.el-divider__text) {
    background-color: #f8f8f8;
  }

  // 协议勾选框警告样式
  :deep(.el-checkbox) {
    &.agreement-warning {
      .el-checkbox__input {
        .el-checkbox__inner {
          border-color: #f56565 !important;
          background-color: #fef2f2 !important;
          animation: shake 0.5s ease-in-out;
        }
      }
    }
  }

  // 抖动动画
  @keyframes shake {
    0%,
    100% {
      transform: translateX(0);
    }
    10%,
    30%,
    50%,
    70%,
    90% {
      transform: translateX(-3px);
    }
    20%,
    40%,
    60%,
    80% {
      transform: translateX(3px);
    }
  }
  .back_svg_view {
    border-radius: 8px;
  }
  .back_svg_view:hover {
    background: #ededed;
  }
  .flex_row {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
  .cancel_btn {
    border-radius: 8px;
    background: var(---2, #e1e2e3);
    backdrop-filter: blur(2px);
    display: flex;
    height: 48px;
    width: 176px;
    justify-content: center;
    align-items: center;
    color: #0a0a0a;
    font-family: 'Inter Tight';
    font-size: 16px;
    font-style: normal;
    font-weight: 500;
    line-height: normal;
  }
  .confirm_btn {
    display: flex;
    height: 48px;
    width: 176px;
    justify-content: center;
    align-items: center;
    border-radius: 8px;
    background: #f76b1b;
    backdrop-filter: blur(2px);
    font-style: normal;
    font-weight: 500;
    line-height: normal;
    color: var(---0, #fff);
    font-family: 'Inter Tight';
    font-size: 16px;
  }
  .agree_content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .agree_view {
    width: 440px;
    background: #fff;
    padding: 32px;
    border-radius: 16px;
    position: absolute;
    top: 50%; /* 顶部距离父容器 50% */
    left: 50%; /* 左侧距离父容器 50% */
    transform: translate(-50%, -50%); /* 向左、上偏移自身 50% */
    z-index: 3000;
    .title {
      color: var(---9, #0a0a0a);
      font-family: 'Inter Tight';
      font-size: 24px;
      font-style: normal;
      font-weight: 700;
      line-height: normal;
    }
    .des_text {
      color: var(---6, #7a7a7a);
      text-align: center;
      font-family: 'Inter Tight';
      font-size: 16px;
      font-style: normal;
      font-weight: 400;
      line-height: 150%; /* 24px */
    }
  }
  .email_text:hover {
    color: #0a0a0a;
    text-decoration: underline;
  }
  .get_code_text {
    color: var(---0, #fff);
    font-family: 'Inter Tight';
    font-size: 16px;
    font-style: normal;
    font-weight: 600;
    line-height: normal;
  }
  .agreement_view {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .color_text {
    color: #f76b1b;
    border-bottom: 1px solid #f76b1b;
    padding-bottom: 1px;
  }
  .color_text:hover {
    color: #e55c0d;
    border-bottom: 1px solid #e55c0d;
  }
</style>
